import { Router } from '@angular/router';
import { Component } from '@angular/core';
import { FormGroup, FormBuilder, Validators } from "@angular/forms";
import { SettingsService } from "@core/services/settings.service";
import {_HttpClient} from "@core/services/http.client";
import {environment} from "../../../../environments/environment";
import {LocalStorageService} from "angular-web-storage";
import {ACLService} from "@core/acl/acl.service";
import {MenuService} from "@core/services/menu.service";

@Component({
  selector: 'app-pages-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.scss']
})
export class LoginComponent {
  valForm: FormGroup;

  constructor(public settings: SettingsService, fb: FormBuilder, private router: Router,
              private http: _HttpClient,
              private aclService: ACLService,
              private menuService: MenuService,
              private local: LocalStorageService) {
    this.valForm = fb.group({
      account: [null, Validators.compose([Validators.required])],
      password: [null, Validators.required],
      remember_me: [null]
    });
  }

  submit() {
    for (const i in this.valForm.controls) {
      this.valForm.controls[i].markAsDirty();
    }
    if (this.valForm.valid) {
      console.log('Valid!');
      console.log(this.valForm.value);
      const url = environment.SERVICE_URL + '/login';
      this.http.post(url, this.valForm.value).subscribe(data => {
          if (this.menuService.menus.length <= 0) {
              const menus = [{text: '业务', group: true, children: data.menus}];
              this.menuService.add(menus);
          }
          this.aclService.setAbility(data.authorities);
          this.menuService.resume();
          this.settings.setUser(data.user);
          this.router.navigate(['/dashboard/v1']);
      });
    }
  }
}
